<template>
  <div class="settings-container">
    <van-nav-bar
      title="设置"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 基本设置 -->
    <div class="settings-section">
      <div class="section-title">基本设置</div>
      <van-cell-group>
        <van-cell title="消息通知" is-link @click="navigateTo('notifications')" />
        <van-cell title="隐私设置" is-link @click="navigateTo('privacy')" />
        <van-cell title="账号安全" is-link @click="navigateTo('security')" />
      </van-cell-group>
    </div>

    <!-- 通用设置 -->
    <div class="settings-section">
      <div class="section-title">通用设置</div>
      <van-cell-group>
        <van-cell center title="系统通知">
          <template #right-icon>
            <van-switch v-model="settings.systemNotify" size="24" @change="onSettingChange('systemNotify')" />
          </template>
        </van-cell>
        <van-cell center title="课程通知">
          <template #right-icon>
            <van-switch v-model="settings.courseNotify" size="24" @change="onSettingChange('courseNotify')" />
          </template>
        </van-cell>
        <van-cell center title="推广通知">
          <template #right-icon>
            <van-switch v-model="settings.promotionNotify" size="24" @change="onSettingChange('promotionNotify')" />
          </template>
        </van-cell>
        <van-cell center title="自动播放">
          <template #right-icon>
            <van-switch v-model="settings.autoPlay" size="24" @change="onSettingChange('autoPlay')" />
          </template>
        </van-cell>
        <van-cell center title="后台播放">
          <template #right-icon>
            <van-switch v-model="settings.backgroundPlay" size="24" @change="onSettingChange('backgroundPlay')" />
          </template>
        </van-cell>
        <van-cell title="清晰度" :value="settings.quality" @click="showQualityPicker = true" />
        <van-cell title="下载路径" :value="settings.downloadPath" />
      </van-cell-group>
    </div>

    <!-- 缓存设置 -->
    <div class="settings-section">
      <div class="section-title">缓存设置</div>
      <van-cell-group>
        <van-cell title="缓存大小" :value="cacheSize" @click="clearCache" />
      </van-cell-group>
    </div>

    <!-- 关于我们 -->
    <div class="settings-section">
      <div class="section-title">关于我们</div>
      <van-cell-group>
        <van-cell title="当前版本" :value="appVersion" />
        <van-cell title="用户协议" is-link @click="navigateTo('terms')" />
        <van-cell title="隐私政策" is-link @click="navigateTo('privacy-policy')" />
        <van-cell title="关于我们" is-link @click="navigateTo('about')" />
        <van-cell v-if="hasUpdate" title="检查更新" is-link @click="checkUpdate" />
      </van-cell-group>
    </div>

    <!-- 退出登录 -->
    <div class="logout-section">
      <van-button
        round
        block
        type="danger"
        @click="showLogoutConfirm"
      >
        退出登录
      </van-button>
    </div>

    <!-- 退出登录确认弹窗 -->
    <van-dialog
      v-model:show="showLogoutDialog"
      title="退出登录"
      show-cancel-button
      @confirm="handleLogout"
    >
      <div class="logout-dialog-content">
        确定要退出登录吗？
      </div>
    </van-dialog>

    <!-- 清晰度选择弹窗 -->
    <van-popup v-model:show="showQualityPicker" position="bottom">
      <van-picker
        :columns="qualityOptionsRef"
        @confirm="onQualityConfirm"
        @cancel="showQualityPicker = false"
        show-toolbar
        title="选择清晰度"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showSuccessToast } from 'vant'

const router = useRouter()

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 用户信息
const userInfo = ref({
  phone: '',
  email: ''
})

// 设置选项
const settings = ref({
  systemNotify: true,
  courseNotify: true,
  promotionNotify: false,
  autoPlay: true,
  backgroundPlay: false,
  quality: '自动',
  downloadPath: '默认路径'
})

// 弹窗控制
const showLogoutDialog = ref(false)
const showQualityPicker = ref(false)

// 应用信息
const appVersion = ref('1.0.0')
const hasUpdate = ref(false)
const cacheSize = ref('0MB')

// 清晰度选项
const qualityOptionsRef = ref([
  { text: '自动', value: 'auto' },
  { text: '流畅', value: 'smooth' },
  { text: '标清', value: 'standard' },
  { text: '高清', value: 'high' },
  { text: '超清', value: 'ultra' }
])

// 页面加载时获取数据
onMounted(async () => {
  try {
    // 获取用户信息
    // const response = await getUserInfo()
    // userInfo.value = response.data

    // 获取设置信息
    // const settingsResponse = await getSettings()
    // settings.value = { ...settings.value, ...settingsResponse.data }

    // 获取缓存大小
    await calculateCacheSize()

    // 检查更新
    await checkUpdate()
  } catch (error) {
    console.error('加载设置页面数据失败:', error)
    showToast('加载数据失败，请重试')
  }
})

// 页面跳转
const navigateTo = (path) => {
  if (path === 'terms') {
    router.push({ name: 'settings-terms' })
  } else if (path === 'privacy-policy') {
    router.push({ name: 'settings-privacy-policy' })
  } else if (path === 'about') {
    router.push({ name: 'settings-about' })
  } else {
    router.push(`/settings/${path}`)
  }
}

// 设置变更处理
const onSettingChange = async (key) => {
  try {
    // await updateSetting({ key, value: settings.value[key] })
    showSuccessToast('设置已更新')
  } catch (error) {
    console.error('更新设置失败:', error)
    showToast('更新设置失败，请重试')
    // 回滚设置
    settings.value[key] = !settings.value[key]
  }
}

// 清晰度选择确认
const onQualityConfirm = (value) => {
  settings.value.quality = value.text
  showQualityPicker.value = false
  onSettingChange('quality')
}

// 清除缓存
const clearCache = async () => {
  try {
    // await clearAppCache()
    cacheSize.value = '0MB'
    showSuccessToast('缓存已清除')
  } catch (error) {
    console.error('清除缓存失败:', error)
    showToast('清除缓存失败，请重试')
  }
}

// 计算缓存大小
const calculateCacheSize = async () => {
  try {
    // const size = await getAppCacheSize()
    // cacheSize.value = formatSize(size)
    cacheSize.value = '23MB'
  } catch (error) {
    console.error('获取缓存大小失败:', error)
    cacheSize.value = '计算失败'
  }
}

// 检查更新
const checkUpdate = async () => {
  try {
    // const response = await checkAppUpdate()
    // hasUpdate.value = response.hasUpdate
    hasUpdate.value = false
  } catch (error) {
    console.error('检查更新失败:', error)
  }
}

// 显示退出确认
const showLogoutConfirm = () => {
  showLogoutDialog.value = true
}

// 处理退出登录
const handleLogout = async () => {
  try {
    // await logout()
    showSuccessToast('已退出登录')
    router.replace('/login')
  } catch (error) {
    console.error('退出登录失败:', error)
    showToast('退出失败，请重试')
  }
}
</script>

<style lang="scss" scoped>
.settings-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 120px; // 增加底部 padding，为 Tabbar 留出空间

  .settings-section {
    margin-bottom: 12px;
    background-color: #fff;

    .section-title {
      padding: 12px 16px;
      font-size: 14px;
      color: #969799;
    }
  }

  .logout-section {
   // position: fixed;
    left: 0;
    right: 0;
    bottom: 70px; // 调整底部位置，确保在 Tabbar 上方
    padding: 0 16px;
    z-index: 10;

    .van-button {
      height: 44px;
      font-size: 16px;
      background: linear-gradient(to right, #ff6b6b, #ff4757);
      border: none;
      
      &:active {
        opacity: 0.9;
      }
    }
  }

  .logout-dialog-content {
    padding: 20px 16px;
    text-align: center;
    color: #323233;
  }
}
</style>
